import { math } from "cc";
import { Entity } from "./Entity";
import { EntityGroup } from "./EntityGroup";

export class EntityGroupManager {
    private _groups: EntityGroup[] = [];
    private _idGroupMap = new Map<number, number>();
    newGroup(id: number, match: (entity: Entity) => boolean) {
        if (this._idGroupMap.has(id)) {
            // 抛出异常
            console.error(`EntityGroupManager: Group id ${id} already exists.`);
            return;
        }
        let group = new EntityGroup(id, match);
        this._idGroupMap.set(id, this._groups.length);
        this._groups.push(group);
    }

    getGroup(id:number) {
        let index = this._idGroupMap.get(id);

        if (index != undefined) {
            return this._groups[index];
        }

        return undefined;
    }

    onEntityAdded(entity: Entity) {
        for (let i = 0; i < this._groups.length; i++) {
            this._groups[i].onEntityAdded(entity);
        }
    }

    onEntityRemove(entity: Entity) {
        for (let i = 0; i < this._groups.length; i++) {
            this._groups[i].onEntityRemove(entity);
        }
    }

    onEntityChanged(entity: Entity) {
        for (let i = 0; i < this._groups.length; i++) {
            this._groups[i].onEntityChanged(entity);
        }
    }
}
